import json

import pymysql
import pymongo
import time
from mydjango.settings import Django_HOST

from django.http import HttpResponse

from .utils import chack_jwt

# 数据库查询
class MysqlQuery:
    def __init__(self, token):
        self.db = pymysql.connect(host=Django_HOST, port=3306, database='workflow', user='root', password="mysql", charset="utf8")
        self.cursor = self.db.cursor()
        self.token = token

    def sql_select(self):

        token = self.token[4:]
        uid = chack_jwt(token).get("uid")


        self.cursor.execute("select a.username,b.name,b.id as relo_id,c.node_id,d.node_name from user a left join role b on a.role_id=b.id left join access c on b.id=c.role_id left join node d on c.node_id=d.id "
                            "where a.id="
                            +str(uid))

        # 获取查询结果
        desc = self.cursor.description
        result = [dict(zip([col[0] for col in desc], row)) for row in self.cursor.fetchall()]
        print(result)
        return result


# 查询用户权限
class UserAuthority:
    def __init__(self, token, type):
        self.token = token
        self.type = type


    # 查询用户管理权限
    def manage_authority(self):
        if self.token:
            result = MysqlQuery(self.token).sql_select()

            if not result:
                return False

                # 如果权限包括用户管理那就可以放行
            for ui in result:
                if ui.get("node_name") == self.type:
                    return True

                elif ui.get("name") == "普通用户":
                    # 如果是普通用户，就查询MongoDB中的属性信息，判断有没有属性权限
                    relo_id = ui.get("relo_id")
                    mango_data = manage_attribute(relo_id)

                    # 判断属性条件是否成立，获取当先小时时间判断是否在允许时间内
                    now_time = time.localtime().tm_hour
                    start_tiem, end_time = mango_data.get("time").split("-")
                    if (int(now_time) >= int(start_tiem)) and (int(now_time) < int(end_time)):
                        return True

        return False


# 在MongoDB查询属性权限信息
def manage_attribute(relo_id):
    mongo_client = pymongo.MongoClient(host=Django_HOST,port=27017)

    # 实例化对象
    db = mongo_client.abac
    table = db.myabac
    # 查询
    res = table.find_one({"roleid":relo_id})

    return res


# 装饰器用户权限验证
def manage_outer(func):

    def manage_inner(request):

        token = request.META.get("HTTP_AUTHORIZATION", None)
        if token:
            result = MysqlQuery(token).sql_select()

            if not result:

                return HttpResponse({"code": "999", "data": "您没有权限"})

            # 如果权限包括用户管理那就可以放行
            for ui in result:
                if ui.get("node_name") == "用户管理":
                    return func(request)

                elif ui.get("name") == "普通用户":
                    # 如果是普通用户，就查询MongoDB中的属性信息，判断有没有属性权限
                    relo_id = ui.get("relo_id")
                    mango_data = manage_attribute(relo_id)

                    # 判断属性条件是否成立，获取当先小时时间判断是否在允许时间内
                    now_time = time.localtime().tm_hour
                    start_tiem, end_time = mango_data.get("time").split("-")
                    if (int(now_time) >= int(start_tiem)) and (int(now_time) < int(end_time)):
                        return func(request)


        return HttpResponse({"code": "999", "data": "您没有权限"})

    return manage_inner


# 装饰器权限工单系统验证
def manage_work(func):

    def manage_inner(request):

        token = request.META.get("HTTP_AUTHORIZATION", None)
        if token:
            result = MysqlQuery(token).sql_select()

            if not result:

                return HttpResponse({"code": "999", "data": "您没有权限"})

            # 如果权限包括用户管理那就可以放行
            for ui in result:
                print(ui.get("node_name"))
                if ui.get("node_name") == "工单系统":
                    print(12222)
                    return func(request)

                elif ui.get("name") == "普通用户":
                    # 如果是普通用户，就查询MongoDB中的属性信息，判断有没有属性权限
                    relo_id = ui.get("relo_id")
                    mango_data = manage_attribute(relo_id)

                    # 判断属性条件是否成立，获取当先小时时间判断是否在允许时间内
                    now_time = time.localtime().tm_hour
                    start_tiem, end_time = mango_data.get("time").split("-")
                    if (int(now_time) >= int(start_tiem)) and (int(now_time) < int(end_time)):
                        return func(request)


        return HttpResponse({"code": "999", "data": "您没有权限"})

    return manage_inner